#include "SwitchWatcher.h"
#include <QDebug>

SwitchWatcher::SwitchWatcher(int pin, QString dev)
	: QObject()
	, m_device(dev)
	, m_pin(pin)
	, m_isSwitchOn(false)
	, m_lastSwitchState(-1)
{
	takePort();
	
	connect(&m_switchPollTimer, SIGNAL(timeout()), this, SLOT(pollSwitch()));
	setPollTime(100);
}

SwitchWatcher::~SwitchWatcher()
{
	releasePort();
}

void SwitchWatcher::setPollTime(int ms)
{
	m_switchPollTimer.setInterval(ms);
}

void SwitchWatcher::takePort()
{
	//Open port and initialize shadow variables
	try {
		m_port.Open(m_device.toStdString());
		//DataWReg = DataRReg = Port.Data();
		m_statRReg = m_port.Stat();
		//CtrlWReg = CtrlRReg = Port.Ctrl();
		
		m_switchPollTimer.start();
		
	} catch (...) {
		qDebug() << "Error opening parallel port";
	};
}

void SwitchWatcher::releasePort()
{
	m_switchPollTimer.stop();
	m_port.Close();
}

void SwitchWatcher::pollSwitch()
{	
	m_statRReg = m_port.Stat();
	
	// Line 13 is i=3
	int i = m_pin - 10;
	
	m_isSwitchOn = !(m_statRReg & (0x01 << (7 - i)));
	
	int thisState = m_isSwitchOn ? 1:0;
	if(thisState != m_lastSwitchState)
		emit switchToggled(m_isSwitchOn);
	
	m_lastSwitchState = thisState;
}
